package lesson01;

/**
 * 顺序打印进阶版
 *
 * @author wileda
 * @date 2023/01/10  13:52
 */
public class Demo12 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Thread t1 = new Thread(() ->{
                ABC.printA();
            });
            t1.start();
           Thread t2 = new Thread(() ->{
               try {
                   ABC.printB();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           });
           t2.start();
           Thread t3 = new Thread(() ->{
               try {
                   ABC.printC();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           });
           t3.start();
        }
    }
}

class ABC{
    //锁住的对象
    private final static Object locker = new Object();
    //a已经执行过了
    private static boolean aExecuted = false;
    //b已经执行过了
    private static boolean bExecuted = false;

    public static void printA(){
        synchronized (locker){
            System.out.print("A");
            //标志a已经完成
            aExecuted = true;
            //唤醒所有等待的线程
            locker.notifyAll();
        }
    }

    public static  void printB() throws InterruptedException {
        synchronized(locker){
            while(!aExecuted) {
                locker.wait();
            }
            System.out.print("B");
            bExecuted = true;
            locker.notifyAll();
        }
    }

    public static void printC() throws InterruptedException {
        synchronized (locker){
            while (!bExecuted){
                locker.wait();
            }
            System.out.print("C");
        }
    }

}
